/*
 * @(#)WorkflowTaskProtectedFilterHelper.java
 *
 * Copyright (c) 2003 DCIVision Ltd
 * All rights reserved.
 *
 * This software is the confidential and proprietary information of DCIVision
 * Ltd ("Confidential Information").  You shall not disclose such Confidential
 * Information and shall use it only in accordance with the terms of the license
 * agreement you entered into with DCIVision Ltd.
 */
package com.dcivision.workflow.core;

import java.sql.Connection;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;

import org.apache.commons.logging.Log;
import org.apache.commons.logging.LogFactory;

import com.dcivision.framework.SessionContainer;
import com.dcivision.framework.Utility;
import com.dcivision.framework.bean.ProtectedObject;
import com.dcivision.framework.bean.ProtectedResource;
import com.dcivision.framework.dao.ProtectedObjectDAObject;
import com.dcivision.framework.dao.ProtectedResourceDAObject;
import com.dcivision.framework.web.DefaultProtectedFilterHelper;
import com.dcivision.workflow.bean.WorkflowProgress;
import com.dcivision.workflow.bean.WorkflowStep;
import com.dcivision.workflow.dao.WorkflowProgressDAObject;
import com.dcivision.workflow.dao.WorkflowStepDAObject;

/**
 * WorkflowTaskProtectedFilterHelper.java
 *
 * @author dick
 * @company DCIVision Limited
*/
public class WorkflowTaskProtectedFilterHelper extends DefaultProtectedFilterHelper {
  
  private static final Log log = LogFactory.getLog(WorkflowTaskProtectedFilterHelper.class);
  
  private Map protectedID = null;
  
  /**
   * Construction
   * 
   * @param sessionContainer
   * @param dbConn The database connection
   */
  public WorkflowTaskProtectedFilterHelper ( SessionContainer sessionContainer, Connection dbConn){
    super ( sessionContainer, dbConn );
  }
  /**
   * Gets url form database
   */
  public void setProtectedResourceList(List protectedResourceList){
    super.setProtectedResourceList(protectedResourceList);
    try {

      if (!Utility.isEmpty(this.getProtectedResourceList())) {
        protectedID = new HashMap();
        for(int i = 0; i < this.getProtectedResourceList().size(); i++) {
          ProtectedResource protectedResource = (ProtectedResource)this.getProtectedResourceList().get(i);
          ProtectedObjectDAObject protectedObjectDAO = new ProtectedObjectDAObject(this.sessionContainer, this.dbConn);
          List objectList = protectedObjectDAO.getListBySourceID(protectedResource.getID());
          if (!Utility.isEmpty(objectList)) {
            for ( int j = 0 ; j < objectList.size() ; j++ ){
            ProtectedObject protectedObject = (ProtectedObject)objectList.get(j);
            protectedID.put(protectedObject.getObjectValue(), protectedObject);
            }
          }
        }
      }
    } catch (Exception ex) {
      log.error(ex, ex);
    } 
  }
  /**
   * determine the permission a specific user has against a specific workflow step
   */
  public boolean isProtected(HttpServletRequest request)throws Exception {
    try {
    	ProtectedResourceDAObject protectedResourceDAO = new ProtectedResourceDAObject(this.sessionContainer, this.dbConn);
      // TODO: We cann't get the value of multiply form's element through the the method "request.getParameter(String key)".
    	String navMode = (request.getParameter("navMode")==null)? "":request.getParameter("navMode");
      String opMode = (request.getParameter("opMode")==null)?"":request.getParameter("opMode");
      if(super.isProtected(request)){
        // check if the requesting URI is protected
        if (protectedID!=null) {
          String objectID = request.getParameter("ID");
          String taglibUrl = (String)request.getSession().getAttribute("ORIGINAL_URL");
          Integer currentStepID = null; 
          if (!Utility.isEmpty(objectID) && !Utility.isEmpty(taglibUrl)) {
            if ("workflow/MaintWorkflowSubmission.do".equals(taglibUrl)) {
              WorkflowStepDAObject stepDAO = new WorkflowStepDAObject(this.sessionContainer, this.dbConn);
              WorkflowStep workflowStep = (WorkflowStep)stepDAO.getSubmitStepByWorkflowRecordID(new Integer(objectID));
              currentStepID = workflowStep.getID();
            } else {
              WorkflowProgressDAObject progressDAO = new WorkflowProgressDAObject(this.sessionContainer, this.dbConn);
              WorkflowProgress workflowProgress = (WorkflowProgress)progressDAO.getObjectByID(new Integer(objectID));
              currentStepID = workflowProgress.getWorkflowStepID();
            }
            if (!Utility.isEmpty(currentStepID) && protectedID.containsKey(currentStepID.toString())) {
            	ProtectedObject protectedObject = (ProtectedObject)protectedID.get(currentStepID.toString());
            	ProtectedResource protectedResource = (ProtectedResource)protectedResourceDAO.getObjectByID(protectedObject.getResourceID());
              request.getSession().setAttribute("Current_Protected_Object", currentStepID);
              // Brook.Huang add start.
              // Compare query URL pattern with protected record definition. 
              // 1. If "NAV_MODE" is definition, check the request url, if contain this "NAV_MODE", return true.
              // 2. If "OP_MODE" is definition, check the request url, if contain this "OP_MODE", return true.
              // TODO: 3. If "OP_MODE" and "NAV_MODE" are not definition, ignor protected check or keep all operation to check? current is ignor choose.
              
              // Condition(1).
              if (!Utility.isEmpty(protectedResource.getNavMode()) && protectedResource.getNavMode().indexOf(navMode) > -1) {
                return true;
              }
              
              // Condition(2).
              if (!Utility.isEmpty(protectedResource.getOpMode()) && protectedResource.getOpMode().indexOf(opMode) > -1) {
                return true;
              }

              return false;
              // Brook.Huang add end.
/* commented by Brook.Huang
//              if (Utility.isEmpty(protectedResource.getNavMode()) && Utility.isEmpty(protectedResource.getOpMode())) {
//                return true;
//              } else if (!Utility.isEmpty(protectedResource.getNavMode()) ) {
//                if ((protectedResource.getNavMode()).indexOf(GlobalConstant.NAV_MODE_EDIT) >= 0 && (protectedResource.getNavMode()).indexOf(GlobalConstant.NAV_MODE_VIEW) >= 0) {
//                  return true;
//                } else if ((protectedResource.getNavMode()).indexOf(GlobalConstant.NAV_MODE_EDIT) >= 0) {
//                	if (!Utility.isEmpty(opMode)) {
//                		return true;
//                	}
//                } else if ((protectedResource.getNavMode()).indexOf(GlobalConstant.NAV_MODE_VIEW) >= 0) {
//                	if (!Utility.isEmpty(navMode) && Utility.isEmpty(opMode)) {
//                		return true;
//                	}
//                }
//              } else {
//              	// TODO protected opMode ;
//              	return false;
//              }
// */
            }
          }
        }
      }
    } catch (Exception ex) {
      log.error(ex, ex);
      return false;
    }
    return false;
  }
}

